<template>
  <div class="main">
    <div @click="visible = true">
      {{ title }}
      <a-icon type="edit" />
    </div>
    <a-modal
      :title="modal_title"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="visible = false"
      :width="820"
    >
      <a-radio-group v-model="type" button-style="solid" @change="typeChange">
        <a-radio-button :value="1">
          全天推广
        </a-radio-button>
        <a-radio-button :value="2">
          指定时段
        </a-radio-button>
      </a-radio-group>
      <m-schedule
        :ref="schedule_ref"
        :value="value"
        :days-title="daysTitle"
        :legend="legend"
        :shortcuts-type="shortcutsType"
        @clear="handleClear"
        @change="handleChange"
        @click="handleClick"
        style="margin-top: 20px;"
        v-if="type == 2"
      >
        <template #hourTip="{day, rowIndex, colIndex}">
          <div>{{ day.name }}-{{ rowIndex }}-{{ colIndex }}</div>
        </template>
        <template #confirm>
          <!-- 默认直接触发 handleConfirm 函数 -->
          {{ handleConfirm() }}
        </template>
      </m-schedule>
    </a-modal>
  </div>
</template>

<script>

export default {
  name:'ScheduleView',
  props:{
    scheduleStr: {
      type: String,
    },
    campaignId:[String, Number],
    userName: [String],
  },
  data() {
    return {
      schedule:[],
      title:'',
      modal_title:'',
      visible: false,
      confirmLoading: false,
      type:1,

      value: {},
      daysTitle:'时段/日期',
      legend: [
        {
          label: '已选时段',
          style: {
            background: 'rgba(0, 82, 204, 0.15)',
            border: '1px solid rgb(0, 82, 204)'
          }
        },
        {
          label: '未选时段',
          style: {
            background: 'rgba(255, 255, 255, 1)',
            border: '1px solid rgb(0, 82, 204)'
          }
        },
      ],
      shortcutsType: 'dropdown',
      ALL_OPTIONS: [
        {label: '投放', value: '投放'},
        {label: '不投放', value: '不投放'}
      ],
      radioValue: '投放',
      
      schedule_ref:'',
    }
  },
  created(){
    this.init()
  },
  mounted(){
  },
  methods:{
    init(){
      // 根据schedule(字符串),设置标题（全天推广或指定时段）与数据 
      try {
        this.schedule_ref = 'schedule-zhibo'
        this.schedule = JSON.parse(this.scheduleStr)
        this.modal_title = '设置推广时段'
        this.setTitle()
        this.set_schedule_to_value()
      } catch (error) {
        console.log(error)
      }
    },
    setTitle(){
      if(this.schedule.length > 0){
        this.title = '指定时段'
        this.type = 2
      }else{
        this.title = '全天推广'
        this.type = 1
      }
    },
    handleOk() {
      let schedule = []
      if(this.type == 2){
        schedule = this.schedule
      }
      this.$emit('confirm', JSON.stringify(schedule))
      this.setTitle()
      this.visible = false
    },

    set_schedule_to_value(){
      // 插件 0对应星期天，此处设置都用此方法， 1 - 7，7 -> 0
      let schedule = this.schedule
      let schedul_obj = {}
      // console.log(schedule)
      // 先把禁推时间算好
      // 格式: {0 : [[0,24]], 1:[[5,9], [15,19]], ...}
      // 再根据禁推时间算value
      for(let item of schedule){
        if(schedul_obj[item['weekDay']]){
          schedul_obj[item['weekDay']].push([item.startHour, item.endHour])
        }else{
          schedul_obj[item['weekDay']] = []
          schedul_obj[item['weekDay']].push([item.startHour, item.endHour])
        }
      }
      // console.log(schedul_obj)
      // 生成value
      let value = {}
      for(let n = 1; n<=7; n++){
        let i = n == 7 ? 0 : n
        let item = schedul_obj[n]  // 此处用 n
        if(!item){
          value[i] = [[0, 23]]
        }else{
          item = item.sort((a,b)=>a[0] - b[0])  // 顺序排序
          let item_end_idx = item.length - 1
          // console.log(item)
          value[i] = []
          if(item[0][0] == 0 && item[item_end_idx][1] >= 23 && item.length == 1){
            continue
          }
          if(item[0][0] > 0){
            value[i].push([0, item[0][0] - 1])
          }
          if(item[item_end_idx][1] <= 24){
            value[i].push([parseInt(item[item_end_idx][1]), 23])
          }
          for(let idx in item){
            idx = parseInt(idx)
            if(idx < item.length - 1){
              let start = parseInt(item[idx][1])
              let end = item[idx + 1][0] - 1
              if(start <= end){
                value[i].push([start, end])
              }
            }
          }
        }
      }
      // console.log(value)
      this.value = value
    },
    set_value_to_schedule(){
      let schedule = []
      let value = this.value
      for(let n = 1; n<=7; n++){
        let i = n == 7 ? 0 : n
        let item = value[i]
        if(item.length == 0){
          schedule.push({
            weekDay: n,
            startHour: 0,
            endHour: 24
          })
        }else{
          let item_end_idx = item.length - 1
          if(item[0][0] > 0){
            schedule.push({
              weekDay: n,
              startHour: 0,
              endHour: item[0][0]
            })
          }
          if(item[item_end_idx][1] < 23){
            schedule.push({
              weekDay: n,
              startHour: parseInt(item[item_end_idx][1]) + 1,
              endHour: 24
            })
          }
          for(let idx in item){
            idx = parseInt(idx)
            if(idx < item.length - 1){
              let start = parseInt(item[idx][1]) + 1
              let end = item[idx + 1][0]
              if(start <= end){
                schedule.push({
                  weekDay: n,
                  startHour: start,
                  endHour: end
                })
              }
            }
          }
        }
      }
      // console.log(schedule)
      this.schedule = schedule
    },
    fillArray(min, max){
      // 补全数组，[2,5] -> [2,3,4,5]
      const result = [];
      for (let i = min; i <= max; i++) {
        result.push(i);
      }
      return result;
    },
    handleConfirm(needClose = true) {
      // console.log(this.$refs[this.schedule_ref])
      const {
        handleAdd,
        handleRemove,
        handleClose,
        value
      } = this.$refs[this.schedule_ref];
      // 先进行 handleRemove 操作，如果value未发生改变，则进行 handleAdd 操作
      handleRemove();
      if(!this.diff_value(value)){
        // 如果没有差异，则进行 handleAdd()
        handleAdd();
      }
      if (needClose) {
        handleClose();
      }
    },
    diff_value(value){
      // value 与 this.value进行比较
      // true 为不一致， false为一致
      // console.log(value, this.value)
      let result = false
      for(let idx in value){
        let item = value[idx]
        let item2 = this.value[idx]
        let item_result = false
        // value中数组为0对应this.value没有这一项
        if(item.length == item2.length){
          for(let k in item){
            let Bitem = item[k]
            let Bitem2 = item2[k]
            if(Bitem[0] != Bitem2[0] || Bitem[1] != Bitem2[1]){
              item_result = true
              break
            } 
          }
          if(item_result){
            result = true
            break
          }
        }else{
          result = true
          break
        }
      }

      return result
    },
    typeChange(){
      if(this.type == 1){
        this.schedule = []
      }else if(this.type == 2){
        this.set_value_to_schedule()
      }
    },
    handleRadioChange(value) {
      this.radioValue = value;
    },
    handleClick(params) {
      console.log(params);
    },
    handleChange(value) {
      // console.log(value)
      // 为了 diff_value 中 value 与 this.value格式一致
      for(let i = 0; i < 7; i++){
        if(!value[i]){
          value[i] = []
        }
      }
      this.value = value;
      this.set_value_to_schedule()
    },
    handleClear() {
    },
  },
  computed: {
    commonCls() {
      return 'schedule-confirm-container';
    }
  },
  watch:{
    visible(val){
      if(val){
        this.init()
      }
    },
    campaignId(){
      this.init()
    }
  }
}
</script>

<style >
.vpro-schedule-confirm-container{
  z-index: 999999 !important;
}
</style>